package com.hdjk.view.activity.personalcenter;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.activity.main.WebBrowseActivity;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.dialog.TextButtonDialog;
import com.hdjk.view.dialog.UpdateDialog;
import com.hdjk.view.entity.IfastUserEntity;
import com.hdjk.view.network.Network;
import com.hdjk.view.network.PersonalNetWork;
import com.hdjk.view.util.CommonUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 用户设置页
 * Created by Administrator on 2017/11/4.
 */

public class AccountSetActivity extends BaseActivity implements View.OnClickListener {
    private TextButtonDialog logoutDialog = null;
    private IfastUserEntity mUser;

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private RelativeLayout rel_personal;
    private RelativeLayout rel_open;
    private TextView tv_open_state;
    private RelativeLayout rel_card;
    private RelativeLayout rel_risk;
    private TextView tv_risk_content;
    private RelativeLayout rel_pwd;
    private RelativeLayout rel_exit;
    private RelativeLayout rel_question;
    private RelativeLayout rel_tel;
    private RelativeLayout rel_version;
    private TextView tv_version_content;
    // End Of Content View Elements

    private UpdateDialog mUpdateDialog = null;

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        rel_personal = (RelativeLayout) findViewById(R.id.rel_personal);
        rel_open = (RelativeLayout) findViewById(R.id.rel_open);
        tv_open_state = (TextView) findViewById(R.id.tv_open_state);
        rel_card = (RelativeLayout) findViewById(R.id.rel_card);
        rel_risk = (RelativeLayout) findViewById(R.id.rel_risk);
        tv_risk_content = (TextView) findViewById(R.id.tv_risk_content);
        rel_pwd = (RelativeLayout) findViewById(R.id.rel_pwd);
        rel_exit = (RelativeLayout) findViewById(R.id.rel_exit);
        rel_question = (RelativeLayout) findViewById(R.id.rel_question);
        rel_tel = (RelativeLayout) findViewById(R.id.rel_tel);
        rel_version = (RelativeLayout) findViewById(R.id.rel_version);
        tv_version_content = (TextView) findViewById(R.id.tv_version_content);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_account_set);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        rel_personal.setOnClickListener(this);
        rel_open.setOnClickListener(this);
        rel_card.setOnClickListener(this);
        rel_risk.setOnClickListener(this);
        rel_pwd.setOnClickListener(this);
        rel_exit.setOnClickListener(this);
        rel_question.setOnClickListener(this);
        rel_tel.setOnClickListener(this);
        rel_version.setOnClickListener(this);
        IntentFilter filter = new IntentFilter(Constant.INTENT_FILTER_STRING_AFTER_IFAST_RISK_TEST);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void initData() {
        if (UserTokenUtil.isOpenAccount(this)) {
            tv_open_state.setText("已开户");
            getUserInfo();
        } else {
            tv_open_state.setText("未开户");
            tv_risk_content.setText("未评测");
        }
        tv_version_content.setText("当前版本："+CommonUtil.getVersionName(this));
    }

    private void getUserInfo() {
        mDialog.show();
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(AccountSetActivity.this));
            PersonalNetWork.getIfastUserInfo(UserTokenUtil.getToken(AccountSetActivity.this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof IfastUserEntity) {
                        mUser = (IfastUserEntity) msg.getData();
                        if (Integer.parseInt(mUser.getRiskAppetite()) < 1) {
                            tv_risk_content.setText("未评测");
                        } else {
                            tv_risk_content.setText(mUser.getRiskAppetiteName());
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.rel_personal:
                intent = new Intent(AccountSetActivity.this, PersonalInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_open:
                if (UserTokenUtil.isOpenAccount(AccountSetActivity.this)) {
                    ToastUtils.showShortToast(AccountSetActivity.this, "您已开户，不能重复开户");
                    return;
                }
                intent = new Intent(AccountSetActivity.this, OpenAccountActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_card:
                if (!UserTokenUtil.isOpenAccount(AccountSetActivity.this)) {
                    ToastUtils.showShortToast(AccountSetActivity.this, "您未开户，请先开户");
                    return;
                }
                intent = new Intent(AccountSetActivity.this, BankCardListActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_risk:
                if (!UserTokenUtil.isOpenAccount(AccountSetActivity.this)) {
                    ToastUtils.showShortToast(AccountSetActivity.this, "您未开户，请先开户");
                    return;
                }
                if (mUser != null && !TextUtils.isEmpty(mUser.getRiskAppetite()) && Integer.parseInt(mUser.getRiskAppetite()) > 0) {
                    intent = new Intent(AccountSetActivity.this, RiskTestReturnActivity.class);
                    intent.putExtra("type", 1);
                    intent.putExtra("risk", mUser.getRiskAppetite());
                    startActivity(intent);
                } else {
                    intent = new Intent(AccountSetActivity.this, RiskTestListActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.rel_pwd:
                intent = new Intent(AccountSetActivity.this, PwdManagerActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_version:
                //检查版本,是否需要更新
                Network.checkUpdate(new CallBackListener() {
                    @Override
                    public void onCallBackCompleted(Msg msg) {
                        boolean flag = false;
                        String[] infos = null;

                        if (msg != null) {
                            if (msg.getSuccess() && msg.getData() != null) {
                                infos = (String[]) msg.getData();
                                try {
                                    if (!TextUtils.isEmpty(infos[4])) {
                                        int code = Integer.valueOf(infos[4]);
                                        if (code > CommonUtil.getVersionCode(AccountSetActivity.this)) {
                                            flag = true;
                                        }
                                    }
                                } catch (Exception e) {
                                }
                            }
                        }
                        final boolean isUpdate = flag;
                        final String[] updateInfo = infos;
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (isUpdate) {
                                    if (mUpdateDialog == null) {
                                        mUpdateDialog = new UpdateDialog(AccountSetActivity.this, new UpdateDialog.UpdateDialogListener() {
                                            @Override
                                            public void onCancel() {

                                            }

                                            @Override
                                            public void onOk() {

                                            }
                                        });
                                    }
                                    // 0：描述 1:是否强制更新 2:下载链接地址 3:标题
                                    if (updateInfo != null) {
                                        mUpdateDialog.showDialog(updateInfo[0], updateInfo[1], updateInfo[2], "版本更新提示");
                                    }
                                } else {
                                    ToastUtils.showShortToast(AccountSetActivity.this,"当前已经是最新版本");
                                }
                            }
                        }, 0);
                    }

                    @Override
                    public void onCallBackError(Msg msg) {

                    }
                });
                break;
            case R.id.rel_exit:
                logoutDialog = new TextButtonDialog(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_cancel:
                                logoutDialog.dismiss();
                                break;
                            case R.id.tv_sure:
                                logoutDialog.dismiss();

//                                mDialog.show();
                                UserTokenUtil.userQuitAction(AccountSetActivity.this);
                                back();
//                                Network.logoutByToken(token, new CallBackListener() {
//                                    @Override
//                                    public void onCallBackCompleted(Msg msg) {
//                                        mDialog.cancel();
//                                        if (msg != null) {
//                                            Toast.makeText(AccountSetActivity.this, msg.getMsg(), Toast.LENGTH_SHORT).show();

                                // 退出登录的时候不管成功还是失败，手机端都应该退出
//                                    if (msg.getSuccess()) {
                                // 停止推送服务 删除别名
//                                            if (!JPushInterface.isPushStopped(SystemSettingActivity.this)) {
//                                                JPushInterface.stopPush(SystemSettingActivity.this);
//                                            }
//                                            JPushInterface.deleteAlias(SystemSettingActivity.this, 0);

                                // 清空登录信息，并跳转到登录页面
//                                            UserTokenUtil.userQuitAction(AccountSetActivity.this);
//                                            back();
//                                    }
//                                        }
//                                    }
//                                });
                                break;
                        }
                    }
                });
                logoutDialog.setDialogContent("是否退出登录", 15);
                logoutDialog.show();
                break;
            case R.id.rel_question:
                intent = new Intent(this, WebBrowseActivity.class);
                intent.putExtra("title", "常见问题");
                intent.putExtra("url", Constant.URL_HELP);
                startActivity(intent);
                break;
            case R.id.rel_tel:
                logoutDialog = new TextButtonDialog(this, R.style.progress_dialog, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_cancel:
                                logoutDialog.dismiss();
                                break;
                            case R.id.tv_sure:
                                logoutDialog.dismiss();
                                if (ActivityCompat.checkSelfPermission(AccountSetActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    // TODO: Consider calling
                                    //    ActivityCompat#requestPermissions
                                    // here to request the missing permissions, and then overriding
                                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                    //                                          int[] grantResults)
                                    // to handle the case where the user grants the permission. See the documentation
                                    // for ActivityCompat#requestPermissions for more details.
                                    ActivityCompat.requestPermissions(AccountSetActivity.this,new String[]{Manifest.permission.CALL_PHONE},789);
                                    return;
                                }
                                Intent intent1 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:0379-60667637"));
                                startActivity(intent1);
                                break;
                        }
                    }
                });
                logoutDialog.setDialogContent("拨打电话0379-60667637？", 15);
                logoutDialog.show();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==789){
            int length = grantResults.length;
            boolean re_request = false;//标记位：如果需要重新授予权限，true；反之，false。
            for (int i = 0; i < length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent1 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:0379-60667637"));
                    startActivity(intent1);
                } else {
                    re_request = true;
                }
                if (re_request){
                    logoutDialog = new TextButtonDialog(this, R.style.progress_dialog, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()) {
                                case R.id.tv_cancel:
                                    logoutDialog.dismiss();
                                    break;
                                case R.id.tv_sure:
                                    logoutDialog.dismiss();
                                    if (ActivityCompat.checkSelfPermission(AccountSetActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                        // TODO: Consider calling
                                        //    ActivityCompat#requestPermissions
                                        // here to request the missing permissions, and then overriding
                                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                        //                                          int[] grantResults)
                                        // to handle the case where the user grants the permission. See the documentation
                                        // for ActivityCompat#requestPermissions for more details.
                                        ActivityCompat.requestPermissions(AccountSetActivity.this,new String[]{Manifest.permission.CALL_PHONE},789);
                                        return;
                                    }
                                    break;
                            }
                        }
                    });
                    logoutDialog.setDialogContent("该操作需要获取打电话权限，是否授权？", 15);
                    logoutDialog.show();
                }
            }
        }
    }

    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constant.INTENT_FILTER_STRING_AFTER_IFAST_RISK_TEST)){
                getUserInfo();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (UserTokenUtil.isOpenAccount(this)) {
            tv_open_state.setText("已开户");
        } else {
            tv_open_state.setText("未开户");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

}
